package com.comment.project.http;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

/**
 * @author liupenghui
 * @date 2018/7/12
 * @desc：
 */
public class HttpUtil {

    public static String get(String url, HttpParams params) {
        String content = "";
//        1. 创建HttpClient对象。
        CloseableHttpClient httpClient = HttpClients.createDefault();
//      2.创建请求方法的实例，并指定请求URL
        HttpGet httpget = new HttpGet(url);
        System.out.println("executing request " + httpget.getURI());
//        3.添加请求参数
///        HttpParams params = new BasicHttpParams();
//        params.setParameter("id", 1);
        httpget.setParams(params);
        try {
//        4.调用HttpClient对象的execute(HttpUriRequest request)发送请求
            CloseableHttpResponse response = null;
                response = httpClient.execute(httpget);
            try {
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                System.out.println("--------------------------------------");
                // 打印响应状态
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    // 打印响应内容长度
                    System.out.println("Response content length: " + entity.getContentLength());
                    // 打印响应内容
                    content =  EntityUtils.toString(entity);
                    System.out.println("Response content: " + content);

                }
                System.out.println("------------------------------------");
            } finally {
                response.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return content;
    }
}
